package me.fung.rem.component

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp

@Composable
fun SearchButton(
    value: String,
    onValueChange: (String) -> Unit,
    modifier: Modifier = Modifier,
    widthIn: Pair<Dp, Dp> = Dp.Unspecified to Dp.Unspecified,
    expand: Boolean = true,
    enabled: Boolean = true,
    autoFocused: Boolean = true,
    direction: LayoutDirection = LayoutDirection.Ltr,
    interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
    content: @Composable BoxScope.() -> Unit,
) {
    var expanded: Boolean by remember { mutableStateOf(expand) }
    Row(
        modifier = modifier,
        verticalAlignment = Alignment.CenterVertically,
    ) {
        AnimatedVisibility(
            visible = expanded && direction == LayoutDirection.Rtl
        ) {
            SearchField(value, onValueChange, widthIn, autoFocused)
        }
        Box(
            modifier = Modifier.clickable(
                onClick = { expanded = !expanded },
                enabled = enabled,
                role = Role.Button,
                interactionSource = interactionSource,
                indication = null
            ),
            contentAlignment = Alignment.Center,
            content = content,
        )
        AnimatedVisibility(
            expanded && direction == LayoutDirection.Ltr
        ) {
            SearchField(value, onValueChange, widthIn, autoFocused)
        }
    }
}

@Composable
private fun SearchField(
    value: String,
    onValueChange: (String) -> Unit,
    widthIn: Pair<Dp, Dp> = Dp.Unspecified to Dp.Unspecified,
    focused: Boolean = true,
) {
    val focusRequester = remember { FocusRequester() }
    if (focused) {
        LaunchedEffect(Unit) {
            focusRequester.requestFocus()
        }
    }
    BasicTextField(
        value = value,
        onValueChange = onValueChange,
        singleLine = true,
        modifier = Modifier.width(IntrinsicSize.Max).height(IntrinsicSize.Max)
            .defaultMinSize(50.dp).padding(start = 10.dp, end = 10.dp).focusRequester(focusRequester)
            .widthIn(widthIn.first, widthIn.second)
    )
}
